package org.fglxy.mockserver.netty;

import org.fglxy.mockserver.entity.WebSocketRegistEventCommand;
import org.fglxy.mockserver.util.JSONUtils;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WebSocketCommandHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
	
	private WebSocketServer server;
	
	public WebSocketCommandHandler(WebSocketServer server) {
		this.server = server;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		String text = msg.text();
		WebSocketRegistEventCommand command = JSONUtils.parse(text, WebSocketRegistEventCommand.class);
		this.server.registMockChangeEvent(command.getMockId(), ctx.channel());
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		server.clearEvent(ctx.channel());
	}

}
